#pragma once 
#include "udp_socket.hpp"
#include <functional>
typedef std::function<void(const std::string& rep, std::string* resp)> Handler;

class udpserver
{
public:
    udpserver(){
        assert(sock_.Socket());
    }
    bool start(const std::string& ip, uint16_t port, Handler handler){
        //1.创建socket
        //2.绑定端口号
        int ret = sock_.Bind(ip, port);
        if(!ret){
            return false;
        }
        //3.进入事件循环
        for(;;)
        {
            //4.尝试读取请求
            std::string rep;
            std::string remote_ip;
            uint16_t remote_port;//保存客户端的地址数据
            bool ret = sock_.RevcFrom(&rep, &remote_ip ,&remote_port);//bool RevcFrom(std::string* buf, std::string* ip = NULL, uint16_t port = NULL)
            if(ret < 0)
            {
                continue;
            }
            std::string resp;
            //5.根据计算请求响应
            handler(rep, &resp);
            //返回响应给客户端
            sock_.SendTo(resp, remote_ip, remote_port);
            printf("[%s:%d] req: %s, resp: %s\n", remote_ip.c_str(), remote_port, rep.c_str(), resp.c_str());
        }
        sock_.Close();
        return true;
    }
    ~udpserver(){
        sock_.Close();
    }
private:
    udpsocket sock_;
};